package com.pirestupppai.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.pirestupppai.R;
import com.pirestupppai.base.BaseActivity;
import com.pirestupppai.bean.BindStatus;
import com.pirestupppai.bean.LoginUser;
import com.pirestupppai.bean.TupaiUser;
import com.pirestupppai.network.NetworkRequest;
import com.pirestupppai.network.TupaiSubscriber;
import com.pirestupppai.utils.OauthUtil;
import com.pirestupppai.utils.Utils;
import com.pirestupppai.utils.WeakReferenceHandler;
import com.pirestupppai.widgets.dialog.ConfirmDialog;
import com.pirestupppai.widgets.dialog.ProgressingDialog;

import java.util.HashMap;

import butterknife.BindView;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * 账号与安全
 *
 * @author: xiaoluo
 * @date: 2017-04-27 17:21
 */
public class AccountSafeActivity extends BaseActivity {

    @BindView(R.id.phone_layout)
    RelativeLayout phoneLayout;
    @BindView(R.id.phone_tv)
    TextView phoneTv;
    @BindView(R.id.bind_tv)
    TextView bindTv;
    @BindView(R.id.revisePw_tv)
    TextView revisePwTv;
    @BindView(R.id.weibo_tb)
    ToggleButton weiboTb;
    @BindView(R.id.wechat_tb)
    ToggleButton wechatTb;
    @BindView(R.id.qq_tb)
    ToggleButton qqTb;

    private static final int OAUTH_ERROR = 500;
    private static final int OAUTH_CANCEL = 600;
    private static final int OAUTH_SUCCESS = 700;

    private WeakReferenceHandler mHandler = new WeakReferenceHandler(this);
    private Platform mPlatform;
    private ProgressingDialog mDialog;
    private String mOauthError = "";

    private boolean isBindQQ = false;
    private boolean isBindWechat = false;
    private boolean isBindWeibo = false;

    @Override
    protected Context getActivityContext() {
        return this;
    }

    @Override
    protected int loadParentLayout() {
        return R.layout.activity_account_safe;
    }

    @Override
    protected void initViews() {
        if (!TextUtils.isEmpty(LoginUser.getInstance().getMobile())) {
            phoneTv.setText("手机号" + LoginUser.getInstance().getMobile());
            bindTv.setText("已绑定");
            phoneTv.setTextColor(getResources().getColor(R.color.gray_text));
            bindTv.setTextColor(getResources().getColor(R.color.gray_text));
            phoneLayout.setEnabled(false);
        } else {
            phoneTv.setText("手机号");
            bindTv.setText("未绑定");
            phoneTv.setTextColor(getResources().getColor(R.color.black));
            bindTv.setTextColor(getResources().getColor(R.color.black));
            phoneLayout.setEnabled(true);
        }

        mDialog = new ProgressingDialog(mContext);
    }

    @Override
    protected void initListeners() {
        phoneLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        revisePwTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(mContext, RevisePasswordActivity.class));
            }
        });

        qqTb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                bindOrDelete(OauthUtil.PLATFORM_QQ, isChecked);
            }
        });

        weiboTb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                bindOrDelete(OauthUtil.PLATFORM_WEIBO, isChecked);
            }
        });

        wechatTb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                bindOrDelete(OauthUtil.PLATFORM_WECHAT, isChecked);
            }
        });
    }

    @Override
    protected void initLogic() {
        NetworkRequest.getInstance().getBindStatus(this,
                new TupaiSubscriber<BindStatus>(mContext) {
                    @Override
                    protected void requestSuccess(BindStatus bindStatus) {
                        if (bindStatus != null) {
                            isBindQQ = bindStatus.isQq();
                            isBindWechat = bindStatus.isWechatOpen();
                            isBindWeibo = bindStatus.isWeibo();
                            qqTb.setChecked(isBindQQ);
                            weiboTb.setChecked(isBindWeibo);
                            wechatTb.setChecked(isBindWechat);
                        }
                    }

                    @Override
                    protected void requestError(String error) {

                    }
                });
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public boolean handleMessage(Message msg) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        switch (msg.what) {
            case OAUTH_ERROR:
                Utils.showToast("授权出错");
                resetTb((String) msg.obj, false);
                break;
            case OAUTH_CANCEL:
                Utils.showToast("取消");
                resetTb((String) msg.obj, false);
                break;
            case OAUTH_SUCCESS:
                oauthBind((String) msg.obj);
                break;
        }
        return super.handleMessage(msg);
    }

    /**
     * 重置状态
     */
    private void resetTb(String name, boolean isCheck) {
        if (name.equals(OauthUtil.PLATFORM_QQ)) {
            qqTb.setChecked(isCheck);
        } else if (name.equals(OauthUtil.PLATFORM_WECHAT)) {
            wechatTb.setChecked(isCheck);
        } else if (name.equals(OauthUtil.PLATFORM_WEIBO)) {
            weiboTb.setChecked(isCheck);
        }
    }

    /**
     * 绑定或解绑
     */
    private void bindOrDelete(String platform, boolean isChecked) {
        if (isChecked) {
            // 三方授权登录
            oauthLogin(platform);
        } else {
            // 解绑
            deleteBind(platform);
        }
    }

    /**
     * 解除绑定
     */
    private void deleteBind(final String platform) {
        ConfirmDialog dialog = new ConfirmDialog(mContext);
        dialog.setMessage("确定要解绑吗?");
        switch (platform){
            case OauthUtil.PLATFORM_QQ:
                if (!isBindQQ) {
                    return;
                }
                break;
            case OauthUtil.PLATFORM_WECHAT:
                if (!isBindWechat) {
                    return;
                }
                break;
            case OauthUtil.PLATFORM_WEIBO:
                if (!isBindWeibo) {
                    return;
                }
                break;
        }

        dialog.setOnSelectListener(new ConfirmDialog.OnSelectListener() {
            @Override
            public void onLeftSelect() {
                resetTb(platform, true);
            }

            @Override
            public void onRightSelect() {
                NetworkRequest.getInstance().deleteBind(mContext, platform,
                        new TupaiSubscriber(mContext) {
                            @Override
                            protected void requestSuccess(Object o) {
                                if (platform.equals(OauthUtil.PLATFORM_QQ)) {
                                    isBindQQ = false;
                                } else if (platform.equals(OauthUtil.PLATFORM_WECHAT)) {
                                    isBindWechat = false;
                                } else if (platform.equals(OauthUtil.PLATFORM_WEIBO)) {
                                    isBindWeibo = false;
                                }
                                Utils.showToast("解绑成功");
                            }

                            @Override
                            protected void requestError(String error) {
                                resetTb(platform, true);
                            }
                        });
            }
        });
        dialog.show();
    }

    /**
     * 第三方授权登录
     */
    private void oauthLogin(final String name) {
        Platform platform = null;
        switch (name) {
            case OauthUtil.PLATFORM_QQ:
                if (isBindQQ) {
                    return;
                }
                platform = ShareSDK.getPlatform(QQ.NAME);
                break;
            case OauthUtil.PLATFORM_WEIBO:
                if (isBindWeibo)
                    return;
                platform = ShareSDK.getPlatform(SinaWeibo.NAME);
                break;
            case OauthUtil.PLATFORM_WECHAT:
                if (isBindWechat)
                    return;
                platform = ShareSDK.getPlatform(Wechat.NAME);
                break;
        }

        mDialog.show();
        platform.SSOSetting(false); //设置false表示使用SSO授权方式,优先调用客户端
        //authorize与showUser单独调用一个即可
        platform.authorize(); //单独授权,OnComplete返回的hashmap是空的
//        platform.showUser(null);//授权并获取用户信息
        if (platform.isAuthValid()) {
            platform.removeAccount(true);
        }

        final Message message = Message.obtain();
        message.obj = name;
        platform.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                mPlatform = platform;
                message.what = OAUTH_SUCCESS;
                mHandler.sendMessage(message);
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                mOauthError = throwable.getMessage();
                message.what = OAUTH_ERROR;
                mHandler.sendMessage(message);
            }

            @Override
            public void onCancel(Platform platform, int i) {
                message.what = OAUTH_CANCEL;
                mHandler.sendMessage(message);
            }
        });
    }

    /**
     * 绑定
     */
    public void oauthBind(final String platformName) {
        PlatformDb platformDb = mPlatform.getDb();
        String accessToken = platformDb.getToken(); // 获取授权token
        String openId = platformDb.getUserId();    // 获取用户在此平台的ID

        NetworkRequest.getInstance().bindThird(this, accessToken, openId, platformName,
                new TupaiSubscriber<TupaiUser>(mContext) {
                    @Override
                    protected void requestSuccess(TupaiUser tupaiUser) {
                        if (platformName.equals(OauthUtil.PLATFORM_QQ)) {
                            isBindQQ = true;
                        } else if (platformName.equals(OauthUtil.PLATFORM_WECHAT)) {
                            isBindWechat = true;
                        } else if (platformName.equals(OauthUtil.PLATFORM_WEIBO)) {
                            isBindWeibo = true;
                        }
                        Utils.showToast("绑定成功");
                    }

                    @Override
                    protected void requestError(String error) {
                        resetTb(platformName, false);
                    }
                });
    }
}
